package com.qmyx.supply.admin.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qmyx.supply.admin.annotation.oplog.annotation.OperationLog;
import com.qmyx.supply.admin.model.request.ImportBankerNoteRequest;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.constants.SysLogConstants;
import com.ytjj.qmyx.supplychain.common.enums.ExceptionOrderClassifyEnum;
import com.ytjj.qmyx.supplychain.common.model.OrderExceptionNoteVO;
import com.ytjj.qmyx.supplychain.common.model.request.ExceptionOrdersRequest;
import com.ytjj.qmyx.supplychain.common.model.response.ExceptionStatisticsResponse;
import com.ytjj.qmyx.supplychain.common.model.response.ImportExcelFailResponse;
import com.ytjj.qmyx.supplychain.common.model.response.OrdersExceptionResponse;
import com.ytjj.qmyx.supplychain.mapper.OrderExceptionNoteMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import com.ytjj.qmyx.supplychain.mapper.model.OrderExceptionNoteReq;
import com.ytjj.qmyx.supplychain.service.BankerService;
import com.ytjj.qmyx.supplychain.service.OrderExceptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 异常订单相关接口
 */
@RestController
@Slf4j
@RequestMapping("/exception/order")
public class BankerExceptionOrderController {
    @Autowired
    private OrderExceptionService orderExceptionService;
    @Autowired
    private BankerService bankerService;
    @Resource
    private OrderExceptionNoteMapper orderExceptionNoteMapper;

    /**
     * 供应商后台-分页获取异常订单
     **/
    @PostMapping("/list")
    public CommonResult queryBankerExceptionOrder(@RequestBody ExceptionOrdersRequest request) {
        log.info("====getExceptionOrders==={}", request);
        YxBanker userInfo = bankerService.getUserInfo();
        request.setBankerId(userInfo.getId());
        request.setRequestType(1);
        CommonPage<OrdersExceptionResponse> commonPage = orderExceptionService.getExceptionOrders(request);
        List<OrdersExceptionResponse> OrdersExceptionResponseList = commonPage.getList();
        Pattern pattern = Pattern.compile("-?[0-9]+(\\\\.[0-9]+)?");
        commonPage.setList(OrdersExceptionResponseList.stream().map(item -> {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (null != item.getCreateTime()) {
                item.setCreateTimeText(simpleDateFormat.format(item.getCreateTime()));
            }
            if (null != item.getHandleTime()) {
                item.setHandleTimeText(simpleDateFormat.format(item.getHandleTime()));
            }
            if (null != item.getOrderCreateTime()) {
                item.setOrderCreateTimeText(simpleDateFormat.format(item.getOrderCreateTime()));
            }
            if (null != item.getUpdateTime()) {
                item.setUpdateTimeText(simpleDateFormat.format(item.getUpdateTime()));
            }
            //脱敏备注人
            List<OrderExceptionNoteVO> exceptionOrderNoteList = item.getExceptionOrderNoteList();
            exceptionOrderNoteList.stream().forEach(e->{
                String adminName = e.getAdminName();
                if(!StringUtils.isEmpty(adminName)){
                    Matcher m = pattern.matcher(adminName);
                    //非id值
                    if(!m.matches()){
                        StringBuffer sb = new StringBuffer(adminName);
                        if(sb.length() > 1){
                            sb.replace(1,2,"*");
                        }
                        e.setAdminName(sb.toString());
                    }
                }
            });
            //脱敏处理人
            String handleName = item.getHandlePerson();
            if(!StringUtils.isEmpty(handleName)){
                Matcher m = pattern.matcher(handleName);
                //非id值
                if(!m.matches()){
                    StringBuffer sb = new StringBuffer(handleName);
                    if(sb.length() > 1){
                        sb.replace(1,2,"*");
                    }
                    item.setHandlePerson(sb.toString());
                }
            }
            item.setBankerName(userInfo.getName());
            return item;
        }).collect(Collectors.toList()));
        return CommonResult.success(commonPage);
    }

    /**
     * 供应商后台-统计异常订单
     **/
    @PostMapping("/getExceptionOrdersStatistics")
    public CommonResult getExceptionOrdersStatistics(@RequestBody ExceptionOrdersRequest request) {
        log.info("====统计异常订单的ExceptionOrdersRequest==={}", request);
        YxBanker userInfo = bankerService.getUserInfo();
        request.setBankerId(userInfo.getId());
        request.setRequestType(1);
        List<ExceptionStatisticsResponse> exceptionOrdersStatistics = orderExceptionService.getExceptionOrdersStatistics(request);
        return CommonResult.success(exceptionOrdersStatistics);
    }

    /**
     * 获取所有异常值列表
     */
    @GetMapping("/getAllExpressException")
    public CommonResult<Map<String, String>> getAllExpressException(){
        Map<String, String> allExpressException = orderExceptionService.getAllExpressException();
        return CommonResult.success(allExpressException);
    }

    /**
     * 供应商后台异常订单-导出异常订单
     * @param response 响应
     * @param request 请求参数实体
     * @return void
     */
    @PostMapping("/exportExceptionOrders")
    public void exportExceptionOrders(HttpServletResponse response, @RequestBody ExceptionOrdersRequest request) {
        orderExceptionService.exportExceptionOrders(response,request);
    }

    /**
     * 供应商异常订单跟踪页--导入excel批量处理
     * @param file
     * @return CommonResult
     */
    @PostMapping("/batchInsertNote")
    @OperationLog(optModule = "供应商异常订单", optType = SysLogConstants.OPERATION_UPDATE, desc = "导入excel批量处理")
    public CommonResult<List<ImportExcelFailResponse>> batchInsertNote(MultipartFile file) throws IOException {
        YxBanker userInfo = bankerService.getUserInfo();
        // 导入订单
        Sheet sheet = new Sheet(1, 1, ImportBankerNoteRequest.class);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
            log.info("表格数据：{}", JSONObject.toJSONString(list));
            OrderExceptionNoteReq req = new OrderExceptionNoteReq();
            req.setAdminName(userInfo.getName());
            List<ImportExcelFailResponse> dealOrdersFail = new ArrayList<>();
            List<ExceptionOrdersRequest> requests = new ArrayList<>();
            for(Object o:list) {
                ImportBankerNoteRequest importBankerNoteRequest = (ImportBankerNoteRequest) o;
                Integer id = importBankerNoteRequest.getId();
                String remark = importBankerNoteRequest.getRemark();
                //未修改指定字段
                if(StringUtils.isEmpty(remark)){
                    continue;
                }
                ExceptionOrdersRequest request = new ExceptionOrdersRequest();
                request.setId(id);
                request.setHandlePerson(userInfo.getId().toString());
                request.setExceptionOrderNote(remark);
                //需求要求不用供应商处理异常订单
//                if ("已处理".equals(statusText)){
//                    request.setStatus((byte) 2);
//                    request.setHandlePerson(userInfo.getId().toString());
//                }
                requests.add(request);
            }
            List<ImportExcelFailResponse> importExcelFailResponses = orderExceptionService.updateExceptionHandle(requests);
            return CommonResult.success(importExcelFailResponses);
        } catch (Exception e) {
            log.info("导入发生异常：{}", e);
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 查询异常处理归类
     * @return
     */
    @GetMapping("/getHandleClassify")
    public CommonResult getHandleClassify() {
        List<Map<Integer,String>> exceptionOrderClassify = ExceptionOrderClassifyEnum.getAllExceptionClassify();
        return  CommonResult.success(exceptionOrderClassify);
    }


    /**
     * 批量归类异常订单
     * @param ids 逗号分割的 id
     * @param type 异常归类 key
     * @return CommonResult
     */
    @PostMapping("/batchDealExceptionOrders")
    public CommonResult batchDealExceptionOrders(Integer[] ids, Integer type) throws IOException {
        return orderExceptionService.batchDealExceptionOrders(ids,type);
    }

}
